import { Controller, Post, Body, HttpCode, HttpStatus, BadRequestException, UnauthorizedException } from '@nestjs/common';
import { AuthService, TokenPair } from '../auth.service';
import { JwtStrategys } from '../strategies/jwt.strategy';
import { ApiProperty } from '@nestjs/swagger';
import { IsString, IsNotEmpty, IsOptional, IsIn } from 'class-validator';

export class RefreshTokenDto {
	@ApiProperty({ example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...' })
	@IsString()
	@IsNotEmpty()
	refresh_token: string;

	@ApiProperty({ example: 'app', enum: ['app', 'admin'], required: false })
	@IsOptional()
	@IsString()
	@IsIn(['app', 'admin'])
	strategy?: keyof typeof JwtStrategys;
}

@Controller('auth')
export class AuthController {
	constructor(private authService: AuthService) { }

	@Post('refresh')
	@HttpCode(HttpStatus.OK)
	async refreshToken(@Body() refreshTokenDto: RefreshTokenDto): Promise<TokenPair> {
		const { refresh_token, strategy = 'app' } = refreshTokenDto;

		if (!refresh_token) {
			throw new BadRequestException('Refresh token is required');
		}

		const tokenPair = await this.authService.refreshToken(refresh_token, strategy);

		if (!tokenPair) {
			// 返回401状态码，提示客户端需要重新登录
			throw new UnauthorizedException('Login session expired, please login again');
		}

		return tokenPair;
	}

	@Post('logout')
	@HttpCode(HttpStatus.OK)
	async logout(@Body() body: { userId: string; tokenId?: string; strategy?: keyof typeof JwtStrategys }): Promise<{ message: string }> {
		const { userId, tokenId, strategy = 'app' } = body;

		if (!userId) {
			throw new BadRequestException('User ID is required');
		}

		if (tokenId) {
			// 撤销特定的refresh token
			await this.authService.revokeRefreshToken(userId, tokenId, strategy);
		} else {
			// 撤销用户所有的refresh token
			await this.authService.revokeAllRefreshTokens(userId, strategy);
		}

		return { message: 'Logged out successfully' };
	}
}
